package top.szhome.system.config;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.ExpressionVisitorAdapter;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.relational.LikeExpression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.*;
import net.sf.jsqlparser.statement.values.ValuesStatement;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * @author 唐加利
 * @date 2023/9/26
 */
@Slf4j
@Configuration
public class MybatisPlusConfiguration {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new LikeEscapeInterceptor());
        return interceptor;
    }

    public static void main(String[] args) throws JSQLParserException {
        Select select = (Select) CCJSqlParserUtil.parse("select u.*, d.name from t_user u left join t_dept d on u.dept_id = d.id where u.id = 9527 and u.username like '%%%'");
        SelectBody body = select.getSelectBody();
        body.accept(new SelectVisitorAdapter() {
            @Override
            public void visit(PlainSelect plainSelect) {
                Expression where = plainSelect.getWhere();
                where.accept(new ExpressionVisitorAdapter() {
                    @Override
                    public void visit(LikeExpression expr) {
                        StringValue right = (StringValue) expr.getRightExpression();
                        String value = right.getValue().replaceAll("(?!^)([%?])(?!$)", "\\\\$1");
                        right.setValue(value);
                        expr.setEscape(new StringValue("\\"));
                    }
                });
            }
        });
        System.out.println(select);
    }
}
